package com.mjw.tender.service;

import com.mjw.tender.api.TbPermissionService;
import com.mjw.tender.api.TbUserService;
import com.mjw.tender.domain.TbPermission;
import com.mjw.tender.domain.TbUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Slf4j
@Component
public class TenderUserDetailsService implements UserDetailsService {

    @Reference(version = "1.0.0")
    private TbUserService tbUserService;

    @Reference(version = "1.0.0")
    private TbPermissionService tbPermissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser tbUser = tbUserService.get(username);
        List<GrantedAuthority> grantedAuthorities = new ArrayList<GrantedAuthority>();

        if (tbUser != null) {
            // 获取用户授权
            List<TbPermission> tbPermissions = tbPermissionService.selectByUserId(tbUser.getId());

            if(tbPermissions == null){
                return null;
            }
            // 声明用户授权
            tbPermissions.forEach(tbPermission -> {
                if (tbPermission != null && tbPermission.getEnname() != null) {
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(tbPermission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
            grantedAuthorities.add(new SimpleGrantedAuthority("User"));//为所有用户都添加一个默认的角色
            // 由框架完成认证工作
            return new User(tbUser.getUsername(), tbUser.getPassword(), grantedAuthorities);
        }

       return null;

    }


}
